<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\message\MessageNotifyController;
use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaDepartment;
use app\model\WaMembers;
use app\model\WaMonthlySettlement;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\controller\wmapi\IndexController;
use app\controller\wmapi\PublicCommentController;
use app\model\WaOrdersPurchaseAmountDetail;
use app\model\WaOrdersPurchaseContract;
use app\model\WaOrdersRelevance;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaOrdersSalesAmountDetail;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaProducts;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchasedVehiclesAmountDetail;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaRegistrationCompany;
use app\model\WaSupplier;
use app\model\WaTransferExportCompany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;
use function GuzzleHttp\json_encode;

class PurchasePayrollRequisitionController extends Validate
{


    /**
     * 采购订单-定金请款
     * 不包括月结
     * @param Request $request
     * @return Response
     */
    public function purchasePayrollRequisitionCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $module_type = 1; //1 采购模块 2 车辆管理模块
        $total_price = 0; // 定金总价金额
        PublicCommentController::采购订单状态;//采购订单状态


        $where_payroll_status_condition = [];

        // 入参验证
        $checkParamCan = PurchasePayrollRequisitionController::checkParamCan($param);
        if ($checkParamCan != 'true'){
            return IndexController::errored('', $checkParamCan);
        }

        // 采购订单编号 获取采购订单信息
        if ($param['purchase_order_sn']) {
            $purchase_order_sn = $param['purchase_order_sn'];
            // 判断采购订单 是否是 待支付定金状态
            $orders_purchase_status_data = WaOrdersPurchase::find(['purchase_order_sn' => $purchase_order_sn]);
            $orders_purchase_status_data = json_decode($orders_purchase_status_data);
//            if ($orders_purchase_status_data) {
//                if ($orders_purchase_status_data->purchase_orders_status != 3)
//                    return IndexController::errored($orders_purchase_status_data->purchase_orders_status, '待支付定金状态，才可以发起定金请款');
//            }


            // 获取采购订单明细详情
            $purchase_amount_condition = [];
            $purchase_amount_condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
            $total_price = WaOrdersPurchaseRelevance::sumByDeposit($purchase_amount_condition); // 定金总价金额

            $where_payroll_status_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];

        } else {
            $purchase_order_sn = '';
        }

        // 判断收款公司类型  收款方类型 1默认是供应商(现版本只有供应商) 2 出口公司（现版本没有）
        $supplier = [];
        $checkCollecting = PurchasePayrollRequisitionController::checkCollectingCompanyCype($supplier,$param);
        if ($checkCollecting != 'true') {
            return IndexController::errored('', $checkCollecting);
        }
        // 付款方类型 1 挂靠公司 2 出口公司 3 其它
        $payment_company = [];
        $check_payment = PurchasePayrollRequisitionController::checkPaymentType($payment_company,$payment_company_name,$param);
        if ($check_payment != 'true') {
            return IndexController::errored('', $check_payment);
        }

        // 创建采购请款订单编号
        $purchase_payroll_sn = 'WMCCGQK' . IndexController::generateOrderSnOther();

        // 验证月结单不能单独请款
//       $checkMonth = PurchasePayrollRequisitionController::checkMonthNotPayroll($purchase_order_sn, $param);
//        if ($checkMonth != 'true'){
//            return IndexController::errored('', $checkMonth);
//        }
        // 判断是否重复请款
        $Pur_back = PurchasePayrollRequisitionController::checkRepeat($param,$where_payroll_status_condition);
        if ($Pur_back != 'true'){
            return IndexController::errored('', $Pur_back);
        }

        // 验证是否还有同比类目款项未完成的请款单（不包括月结）

        PublicCommentController::请款单请款结算类型;
        //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
        $status = 1;
        $pur_pay_re_condition = [];
        $pur_pay_re_condition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
        $pur_pay_re_condition [] = ['payroll_requisition_type','=',1];

        $requested_price = WaPurchasePayrollRequisition::sums($pur_pay_re_condition);
        if ($requested_price){
            $requested_price = round($requested_price,2);
        }

        $param['this_request_price'] = 0;
        // 创建采购请款单数据
        $payroll_requisition_data = [
            'supplier_id' => $param['supplier_id'], // 收款公司id
            'supplier_type' => $param['supplier_type'], // 收款公司类型

            'payroll_requisition_type' => 1, //请款类型
            'purchase_payroll_sn' => $purchase_payroll_sn, //采购请款编号
            'admin_id' => $adminId->id, //管理员id
            'admin_name' => $adminId->nickname, //管理员名称
            'purchase_order_sn' => $purchase_order_sn, //采购请款单编号
            'payment_company_type' => $param['payment_company_type'], // 付款方类型 1 挂靠公司 2 出口公司 3 其它
            'payment_company_name' => $payment_company_name, // 付款公司名称
            'price_name' => $param['price_name'], //款项名称
            'total_price' => round($total_price, 2), //总金额
            'requested_price' => $requested_price, //已请款金额
            'this_request_price' => round($total_price, 2), //本次请款金额
            'remark' => $param['remark'],
            'status' => $status,
            'created_at' => dateTime(),

        ];

        if ($param['voucher']){

            $payroll_requisition_data['voucher'] = json_encode($param['voucher']); // 凭证
        }


        if ($param['payment_company_type'] != 3){
            $payroll_requisition_data['payment_id'] = $param['payment_id'];// 付款公司id
        }

        // 创建采购请款单其它数据
        PurchasePayrollRequisitionController::addCansByCreated($payroll_requisition_data,$supplier,$param);

        \support\Db::beginTransaction();
        try {
            $res = WaPurchasePayrollRequisition::created($payroll_requisition_data);
            // 提交审批   超出采购金额  端午前改版了  所有金额都需要审批
            $approve_add = ApproveSettingController::payrollApproveAdd($adminId, $total_price, $param, $purchase_payroll_sn, $purchase_order_sn);
            if ($approve_add != 'true'){
                return IndexController::errored('', $approve_add);
            }


            // 查询请款单中的审批编号
            $payroll_find_condition = [];
            $payroll_find_condition [] = ['purchase_payroll_sn','=',$purchase_payroll_sn];
            $payroll_find = WaPurchasePayrollRequisition::find($payroll_find_condition);
            $payroll_find = json_decode($payroll_find);
            if (!$payroll_find){
                return IndexController::errored('', '请款编号查询失败');
            }


            //更新 采购订单定金请款审批编号
            $up_purchase_payment_status_condition = [];
            $up_purchase_payment_status_condition [] = ['purchase_order_sn','=',$purchase_order_sn];
            $up_purchase_payment_status_data = [
                'deposit_pr_no' => $payroll_find->pr_no,
                'deposit_purchase_payroll_sn' => $purchase_payroll_sn,
//                'deposit_payment_status' => 2,
                'updated_at' => dateTime(),
            ];
            $up_purchase_payment_status = WaOrdersPurchase::updated($up_purchase_payment_status_data,$up_purchase_payment_status_condition);

            if (!$up_purchase_payment_status){
                return IndexController::errored('', '采购订单尾款请款编号同步失败');
            }

            // 同步 定金 到车辆费用明细
            $data_by_deposit = [
//                'vin' => $param['vin'], // 车架号
                'price_name' => '定金费用', // 费用名称
                'total_price' => $total_price, // 定金费用
                'currency' => 1, // 货币类型   1人民币 2美元
                'vehicles_type' => 1, // 车务类型 1 采购车务 2 跟单车务
                'payment_type' => 1, // 支付方式  1 现结 2 月结
                'payment_status' => 0, // 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
                'supplier_id' => $param['supplier_id'],
                'supplier_type' => $param['supplier_type'], //
                'supplier_type_name' => '车辆供应商', //
                'supplier_name' => $supplier->name,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];

            $res_by_deposit_add = WaPurchasedVehiclesAmountDetail::created($data_by_deposit);
            if (!$res_by_deposit_add) {

                return IndexController::successed('', '车辆定金费用明细添加失败');
            }
            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '现结付款', // 标题
                        'markdown' => '采购-定金请款'.$time, // 内容
                    ];
                    $currentRoute  = $request->host();

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }
            \support\Db::commit();
            return IndexController::successed($res, '采购请款单创建成功');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasePayrollRequisitionCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '采购请款单创建失败');
        }

    }

    /**
     *采购订单-尾款单请款
     * 不包括月结
     * @param Request $request
     * @return Response
     */
    public function purchasePayrollRequisitionByBalance(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $module_type = 1; //1 采购模块 2 车辆管理模块
        $total_price = 0; // 定金总价金额
        PublicCommentController::采购订单状态;//采购订单状态


        $where_payroll_status_condition = [];

        // 入参验证
        $checkParamCan = PurchasePayrollRequisitionController::checkParamCan($param);
        if ($checkParamCan != 'true'){
            return IndexController::errored('', $checkParamCan);
        }

        // 采购订单编号 获取采购订单信息
        if ($param['purchase_order_sn']) {
            $purchase_order_sn = $param['purchase_order_sn'];
            // 判断采购订单 是否是 待支付定金状态
            $orders_purchase_status_data = WaOrdersPurchase::find(['purchase_order_sn' => $purchase_order_sn]);
            $orders_purchase_status_data = json_decode($orders_purchase_status_data);
//            if ($orders_purchase_status_data) {
//                if ($orders_purchase_status_data->purchase_orders_status != 11)
//                    return IndexController::errored($orders_purchase_status_data->purchase_orders_status, '待支付尾款状态，才可以发起尾款请款');
//            }


            // 获取采购订单明细详情
            $purchase_amount_condition = [];
            $purchase_amount_condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
            $total_price_by_balance = $orders_purchase_status_data->balance_total_price;
            $where_payroll_status_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];

        } else {
            $purchase_order_sn = '';
        }

        // 判断收款公司类型  收款方类型 1默认是供应商(现版本只有供应商) 2 出口公司（现版本没有）
        $supplier = [];
        $checkCollecting = PurchasePayrollRequisitionController::checkCollectingCompanyCype($supplier,$param);
        if ($checkCollecting != 'true') {
            return IndexController::errored('', $checkCollecting);
        }
        // 付款方类型 1 挂靠公司 2 出口公司 3 其它
        $payment_company = [];
        $check_payment = PurchasePayrollRequisitionController::checkPaymentType($payment_company,$payment_company_name,$param);
        if ($check_payment != 'true') {
            return IndexController::errored('', $check_payment);
        }


        // 创建采购请款订单编号
        $purchase_payroll_sn = 'WMCCGQK' . IndexController::generateOrderSnOther();

//        // 验证月结单不能单独请款
//        $checkMonth = PurchasePayrollRequisitionController::checkMonthNotPayroll($purchase_order_sn, $param);
//        if ($checkMonth != 'true'){
//            return IndexController::errored('', $checkMonth);
//        }
        // 判断是否重复请款
        $Pur_back = PurchasePayrollRequisitionController::checkRepeat($param,$where_payroll_status_condition);
        if ($Pur_back != 'true'){
            return IndexController::errored('', $Pur_back);
        }

        // 验证是否还有同比类目款项未完成的请款单（不包括月结）

        PublicCommentController::请款单请款结算类型;
        //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
        $status = 1;
        $pur_pay_re_condition = [];
        $pur_pay_re_condition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
        $pur_pay_re_condition [] = ['payroll_requisition_type','=',2];

        $requested_price = WaPurchasePayrollRequisition::sums($pur_pay_re_condition);
        if ($requested_price){
            $requested_price = round($requested_price,2);
        }
        $param['this_request_price'] = 0;
        // 创建采购请款单数据
        $payroll_requisition_data = [

            'payroll_requisition_type' => 2, //请款类型
            'purchase_payroll_sn' => $purchase_payroll_sn, //采购请款编号
            'admin_id' => $adminId->id, //管理员id
            'admin_name' => $adminId->nickname, //管理员名称
            'purchase_order_sn' => $purchase_order_sn, //采购请款单编号
            'created_at' => dateTime(),
            'status' => $status,
            'total_price' => round($total_price_by_balance, 2), //总金额
            'requested_price' => $requested_price, //已请款金额
            'this_request_price' => round($total_price_by_balance, 2), //本次请款金额
            'price_name' => $param['price_name'], //款项名称
            'payment_company_name' => $payment_company_name, // 付款公司名称
            'supplier_id' => $param['supplier_id'], // 收款公司id
            'payment_company_type' => $param['payment_company_type'], // 付款方类型 1 挂靠公司 2 出口公司 3 其它

        ];

        if ($param['payment_company_type'] != 3){
            $payroll_requisition_data['payment_id'] = $param['payment_id'];// 付款公司id
        }

        // 创建采购请款单其它数据
        PurchasePayrollRequisitionController::addCansByCreated($payroll_requisition_data,$supplier,$param);
        \support\Db::beginTransaction();
        try {
            $res = WaPurchasePayrollRequisition::created($payroll_requisition_data);
            // 提交审批   超出采购金额  端午前改版了  所有金额都需要审批
            $approve_add = ApproveSettingController::payrollApproveAdd($adminId, $total_price_by_balance, $param, $purchase_payroll_sn, $purchase_order_sn);
            if ($approve_add != 'true'){
                return IndexController::errored('', $approve_add);
            }

            // 查询请款单中的审批编号
            $payroll_find_condition = [];
            $payroll_find_condition [] = ['purchase_payroll_sn','=',$purchase_payroll_sn];
            $payroll_find = WaPurchasePayrollRequisition::find($payroll_find_condition);
            $payroll_find = json_decode($payroll_find);
            if (!$payroll_find){
                return IndexController::errored('', '请款编号查询失败');
            }



            //更新 采购订单尾款请款审批编号
            $up_purchase_payment_status_condition = [];
            $up_purchase_payment_status_condition [] = ['purchase_order_sn','=',$purchase_order_sn];
            $up_purchase_payment_status_data = [
                'balance_pr_no' => $payroll_find->pr_no,
                'balance_purchase_payroll_sn' => $purchase_payroll_sn,
//                'balance_payment_status' => 2,
                'updated_at' => dateTime(),
            ];
            $up_purchase_payment_status = WaOrdersPurchase::updated($up_purchase_payment_status_data,$up_purchase_payment_status_condition);
            if (!$up_purchase_payment_status){
                return IndexController::errored('', '采购订单尾款请款编号同步失败');
            }


            // 同步 尾款 到车辆费用明细
            $data_by_balance = [
//                'vin' => $param['vin'], // 车架号
                'price_name' => '尾款费用', // 费用名称
                'total_price' => $total_price_by_balance, // 每辆车尾款费用
                'currency' => 1, // 货币类型   1人民币 2美元
                'vehicles_type' => 1, // 车务类型 1 采购车务 2 跟单车务
                'payment_type' => 1, // 支付方式  1 现结 2 月结
                'payment_status' => 0, // 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
                'supplier_id' => $param['supplier_id'],
                'supplier_type' => 1, //
                'supplier_type_name' => '车辆供应商', //
                'supplier_name' => $supplier->name,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];

            $res_by_balance_add = WaPurchasedVehiclesAmountDetail::created($data_by_balance);
            if (!$res_by_balance_add) {

                return IndexController::successed('', '车辆尾款费用明细添加失败');
            }
            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '现结付款', // 标题
                        'markdown' => '采购-尾款请款'.$time, // 内容
                    ];
                    $currentRoute  = $request->host();

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed($res, '采购尾款请款单创建成功');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasePayrollRequisitionByBalance', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '采购尾款请款单创建失败');
        }

    }

    // 验证是否还有同比类目款项未完成的请款单（不包括月结）
    public static function checkRepeat($param,$where_payroll_status_condition){
        $where_payroll_status_condition [] = ['price_name', '=', $param['price_name']];
        $where_payroll_status_condition [] = ['status', '<', 3]; //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
        $where_payroll_status_condition [] = ['payroll_requisition_type', '=', 1]; // 请款类型
        $check_all = WaPurchasePayrollRequisition::allByPur($where_payroll_status_condition);
        $check_all = json_decode($check_all);
        if ($check_all) {
            return '请先完成上一笔该订单的请款';
        }
        if ($param['price_name'] == '采购定金'){
            //判断定金请款只能一次不能重复  请款状态  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
            $where_payroll_status_condition [] = ['status','<', 4];
            $check_all = WaPurchasePayrollRequisition::allByPur($where_payroll_status_condition);
            $check_all = json_decode($check_all);
            if ($check_all) {
                return '定金重复请款';
            }
        }
        return 'true';
    }

    public static function addCansByCreated(&$payroll_requisition_data,$supplier,$param){
        if (array_key_exists('payment_company_info', $param)) {
            $payroll_requisition_data['payment_company_info'] = json_encode($param['payment_company_info']);
        }

        if (array_key_exists('collecting_company_info', $param)) {
            $payroll_requisition_data['collecting_company_info'] = json_encode($param['collecting_company_info']);
        }

        if (array_key_exists('payment_details', $param)) {
            $payroll_requisition_data['payment_details'] = json_encode($param['payment_details']);
        }

        if (array_key_exists('supplier_type', $param)) {
            $payroll_requisition_data['supplier_type'] = $param['supplier_type'];
        }

        if (array_key_exists('voucher', $param)) {
            if ($param['voucher']) {
                $payroll_requisition_data['voucher'] = json_encode($param['voucher']);
            } else {
//                $payroll_requisition_data['voucher'] = [];
            }
        } else {
//            $payroll_requisition_data['voucher'] = [];
        }

        if ($supplier) { // 收款方
            $payroll_requisition_data['supplier_id'] = intval($supplier->id);
            $payroll_requisition_data['supplier_name'] = $supplier->name;
            $payroll_requisition_data['supplier_type'] = $param['supplier_type'];
        }

    }

    public static function checkPaymentType(&$payment_company,&$payment_company_name,&$param){
        if ($param['payment_company_type'] == 1){
            $payment_company_condition = [];
            $payment_company_condition [] = ['id','=',$param['payment_id']];
            $payment_company = WaRegistrationCompany::find($payment_company_condition);
            $payment_company = json_decode($payment_company);
            if (!$payment_company){
                return '付款方信息获取失败';
            }
            $payment_company_name = $payment_company->name;
        }elseif ($param['payment_company_type'] == 2){
            $payment_company_condition = [];
            $payment_company_condition [] = ['id','=',$param['payment_id']];
            $payment_company = WaTransferExportCompany::find($payment_company_condition);
            $payment_company = json_decode($payment_company);
            if (!$payment_company){
                return '付款方信息获取失败';
            }
            $payment_company_name = $payment_company->name;
        }elseif ($param['payment_company_type'] == 3){
            $param['payment_id'] = '';
            $payment_company_name = $param['payment_company_name'];
        }
        return 'true';
    }

    public static function checkCollectingCompanyCype(&$supplier,$param){
        if (array_key_exists('collecting_company_type', $param)) {
            if ($param['collecting_company_type'] == 1 ) {

            }elseif ($param['collecting_company_type'] == 2){

            } else {
                return '不存在改收款类型';
            }
        } else {
            // 判断收款公司类型 1默认是供应商(现版本只有供应商)
            //获取供应商信息
            if (array_key_exists('supplier_id', $param) && array_key_exists('supplier_type', $param)) {
                if ($param['supplier_type'] && $param['supplier_id']) {
                    $supplier = IndexController::supplierDetailCommon($param['supplier_type'], $param['supplier_id']);
                    $supplier = json_decode($supplier);
                    if (!$supplier) {
                        return '供应商详情获取失败';
                    }
                } else {
                    return '缺少必要入参-> 供应商 type / id';
                }
            } else {
                return '缺少必要入参-> 供应商 type / id';
            }

        }
        return 'true';
    }

    public static function checkParamCan(&$param)
    {

        // 币种
        if (!array_key_exists('currency', $param)) {
            $param['currency'] = '';
        }
        // 汇率
        if (!array_key_exists('cnh', $param)) {
            $param['cnh'] = 0;
        }
        // 开票类型
//        if (!array_key_exists('billing_type', $param)) {
//            $param['billing_type'] = '';
//        }
        // 总额
        if (!array_key_exists('payment_account', $param)) {
            $param['payment_account'] = 0;
        }
        // 款项名称
        if (!array_key_exists('price_name', $param)) {
            return '款项名称,必传';

        }

        return 'true';

    }

    // 定金/ 尾款 款项是否月结 验证
    public static function checkMonthNotPayroll($purchase_order_sn, $param)
    {
        $where_payroll_status = [];
        if ($purchase_order_sn) {
            $orders_purchase = WaOrdersPurchase::find(['purchase_order_sn' => $purchase_order_sn]);
            $orders_purchase = json_decode($orders_purchase);
            if (!$orders_purchase) {
                return '获取采购订单信息失败';
            }
            $where_payroll_status [] = ['purchase_order_sn', '=', $purchase_order_sn];
            // 判断是否月结
            $where_monthly_settlement = [];
            $where_monthly_settlement [] = ['purchase_order_sn', '=', $purchase_order_sn];
            $where_monthly_settlement [] = ['price_name', '=', $param['price_name']];
            $where_monthly_settlement [] = ['is_monthly_settlement', '=', 2]; // 是否月结 1 否 2 是
            $orders_monthly_settlement = WaOrdersPurchaseAmountDetail::find($where_monthly_settlement);
            $orders_monthly_settlement = json_decode($orders_monthly_settlement);
            if ($orders_monthly_settlement) {
                return '月结款项不可单独请款';
            }
        }

        return 'true';
    }

    // 验证月结单不能单独请款
    public static function checkMonthNotPayrollByVin($param)
    {
        if ($param['vin']) {
            // 判断是否月结
            $where_monthly_settlement = [];
            $where_monthly_settlement [] = ['vin', '=', $param['vin']];
            $where_monthly_settlement [] = ['price_name', '=', $param['price_name']];
            $where_monthly_settlement [] = ['payment_type', '=', 2]; // 支付方式  1 现结 2 月结
            $orders_monthly_settlement = WaPurchasedVehiclesAmountDetail::find($where_monthly_settlement);
            $orders_monthly_settlement = json_decode($orders_monthly_settlement);
            if ($orders_monthly_settlement) {
                return '月结款项不可单独请款';
            }
        }

        return 'true';
    }





    /**
     * 车辆管理-车务请款
     * 不包括月结
     * @param Request $request
     * @return Response
     */
    public function payrollRequisitionByCarServiceCreate(Request $request)
    {
        //  process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $total_price = 0; // 定金总价金额
        PublicCommentController::采购订单状态;//采购订单状态

        $where_payroll_status_condition = [];
        $where_payroll_status_condition [] = ['vin', '=', $param['vin']]; //采购请款单编号

        // 入参验证
        $checkParamCan = PurchasePayrollRequisitionController::checkParamCan($param);
        if ($checkParamCan != 'true'){
            return IndexController::errored('', $checkParamCan);
        }

        // 判断收款公司类型  收款方类型 1默认是供应商(现版本只有供应商) 2 出口公司（现版本没有）
        $supplier = [];
        $checkCollecting = PurchasePayrollRequisitionController::checkCollectingCompanyCype($supplier,$param);
        if ($checkCollecting != 'true') {
            return IndexController::errored('', $checkCollecting);
        }
        // 付款方类型 1 挂靠公司 2 出口公司 3 其它
        $payment_company = [];
        $check_payment = PurchasePayrollRequisitionController::checkPaymentType($payment_company,$payment_company_name,$param);
        if ($check_payment != 'true') {
            return IndexController::errored('', $check_payment);
        }
        // 创建采购请款订单编号
        $purchase_payroll_sn = 'WMCCGQK' . IndexController::generateOrderSnOther();

        // 验证月结单不能单独请款
        $checkMonth = PurchasePayrollRequisitionController::checkMonthNotPayrollByVin($param);
        if ($checkMonth != 'true'){
            return IndexController::errored('', $checkMonth);
        }
        // 判断是否重复请款
        $Pur_back = PurchasePayrollRequisitionController::checkRepeat($param,$where_payroll_status_condition);
        if ($Pur_back != 'true'){
            return IndexController::errored('', $Pur_back);
        }

        // 验证是否还有同比类目款项未完成的请款单（不包括月结）

        PublicCommentController::请款单请款结算类型;
        //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
        $status = 1;
        $pur_pay_re_condition = [];
        $pur_pay_re_condition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
        $pur_pay_re_condition [] = ['payroll_requisition_type','=',4];

        $requested_price = WaPurchasePayrollRequisition::sums($pur_pay_re_condition);
        if ($requested_price){
            $requested_price = round($requested_price,2);
        }
        $param['this_request_price'] = 0;
        // 创建采购请款单数据
        $payroll_requisition_data = [
            'supplier_id' => $param['supplier_id'], // 收款公司id
            'supplier_type' => $param['supplier_type'], // 收款公司类型

            'payroll_requisition_type' => 1, //请款类型
            'purchase_payroll_sn' => $purchase_payroll_sn, //采购请款编号
            'admin_id' => $adminId->id, //管理员id
            'admin_name' => $adminId->nickname, //管理员名称
            'vin' => $param['vin'], //采购请款单编号
            'payment_company_type' => $param['payment_company_type'], // 付款方类型 1 挂靠公司 2 出口公司 3 其它
            'payment_company_name' => $payment_company_name, // 付款公司名称
            'payment_id' => $param['payment_id'], // 付款公司id
            'price_name' => $param['price_name'], //款项名称
            'total_price' => round($total_price, 2), //总金额
            'requested_price' => $requested_price, //已请款金额
            'this_request_price' => round($total_price, 2), //本次请款金额
            'remark' => $param['remark'],
            'status' => $status,
            'created_at' => dateTime(),

        ];

        if ($param['payment_company_type'] != 3){
            $payroll_requisition_data['payment_id'] = $param['payment_id'];// 付款公司id
        }

        if (array_key_exists('payment_company_info',$param)){
            $payroll_requisition_data['payment_company_info'] = json_encode($param['payment_company_info']);
        }

        if (array_key_exists('collecting_company_info',$param)){
            $payroll_requisition_data['collecting_company_info'] = json_encode($param['collecting_company_info']);
        }



        // 创建采购请款单其它数据
        PurchasePayrollRequisitionController::addCansByCreated($payroll_requisition_data,$supplier,$param);
        \support\Db::beginTransaction();
        try {
            $res = WaPurchasePayrollRequisition::created($payroll_requisition_data);
            // 提交审批
            //获取采购订单编号
            $purchase_order_find = [];
            $purchase_order_find [] = ['vin','=',$param['vin']];
            $purchase_order_find = WaPurchasedVehicles::find($purchase_order_find);
            $purchase_order_find = json_decode($purchase_order_find);
            if (!$purchase_order_find){
                return IndexController::successed($res, '车辆信息查询失败');
            }
            $purchase_order_sn = $purchase_order_find->purchase_order_sn;
            $approve_add_vin = ApproveSettingController::payrollApproveAddByVin($adminId, $total_price, $param, $purchase_payroll_sn, $purchase_order_sn, $param['vin']);
            if ($approve_add_vin != 'true'){
                return IndexController::errored('', $approve_add_vin);
            }

            // 修改状态 车务请款明细状态
            PublicCommentController::请款单状态;
            PublicCommentController::车辆明细付款类型;
            $vehicles_amount_detail_data = [
                'payment_status' => 1,
                'purchase_payroll_sn' => $purchase_payroll_sn, //采购请款编号
                'updated_at' => dateTime(),

            ];
            $vehicles_amount_detail_condition = [];
            $vehicles_amount_detail_condition [] = ['vin', '=', $param['vin']];
            $vehicles_amount_detail_condition [] = ['price_name', '=', $param['price_name']]; //款项名称;
            $vehicles_amount_detail_up =  WaPurchasedVehiclesAmountDetail::updated($vehicles_amount_detail_data,$vehicles_amount_detail_condition);
            if (!$vehicles_amount_detail_up){
                return IndexController::successed($res, '车务请款明细状态修改失败');
            }

            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '现结付款', // 标题
                        'markdown' => '车务请款'.$time, // 内容
                    ];
                    $currentRoute  = $request->host();

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }
            \support\Db::commit();
            return IndexController::successed($res, '车务请款单创建成功');
        } catch (\Throwable $exception) {

            IndexController::logError('payrollRequisitionByCarServiceCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '车务请款单创建失败');
        }


    }

    /**
     * 月结账单请款
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementPayrollReurchaseCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $param['price_name'] = '月结请款';

        $pur_pay_re_condition = [];
        $pur_pay_re_condition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
        $pur_pay_re_condition [] = ['payroll_requisition_type','=',3];

        $requested_price = WaPurchasePayrollRequisition::sums($pur_pay_re_condition);
        if ($requested_price){
            $requested_price = round($requested_price,2);
        }
        // 入参验证
        $checkParamCan = PurchasePayrollRequisitionController::checkParamCan($param);
        if ($checkParamCan != 'true'){
            return IndexController::errored('', $checkParamCan);
        }


        /**
         * 月结请款 不能结当前月  和  当前月之前的月份
         */
        // 获取当前月的 开始时间
        $firstDayOfMonth =  strtotime(date('Y-m-d', strtotime('first day of this month')));
        // 获取当前月结账单
        $month_settlement_data = [];
        $month_settlement_data [] = ['bill_number','=',$param['bill_number']];
        $month_settlement_data = WaMonthlySettlement::find($month_settlement_data);
        $month_settlement_data = json_decode($month_settlement_data);
        if (!$month_settlement_data){
            return IndexController::errored('','月结账单信息获取失败');
        }
        if ($month_settlement_data->first_day_of_month >= $firstDayOfMonth){
            echo $firstDayOfMonth;
            echo $month_settlement_data->first_day_of_month;
            echo $month_settlement_data->year_month;
//            return IndexController::errored('','只能结(当前月之前的月份账单)');
        }


        // 判断收款公司类型  收款方类型 1默认是供应商(现版本只有供应商) 2 出口公司（现版本没有）
        $supplier = [];
        $checkCollecting = PurchasePayrollRequisitionController::checkCollectingCompanyCype($supplier,$param);
        if ($checkCollecting != 'true') {
            return IndexController::errored('', $checkCollecting);
        }
        // 付款方类型 1 挂靠公司 2 出口公司 3 其它
        $payment_company = [];
        $check_payment = PurchasePayrollRequisitionController::checkPaymentType($payment_company,$payment_company_name,$param);
        if ($check_payment != 'true') {
            return IndexController::errored('', $check_payment);
        }
        $purchase_payroll_sn = 'WMYJQK' . IndexController::generateOrderSnOther();

        $month = intval(date("m",time()));
        $year = intval(date("Y",time()));
        //供应商id
        if (array_key_exists('supplier_id', $param) && array_key_exists('supplier_type', $param)) {
            if ($param['supplier_type']  && $param['supplier_id']){
                $supplier = IndexController::supplierDetailCommon($param['supplier_type'],$param['supplier_id']);
                if (!$supplier) {

                    return IndexController::error_by_static($supplier, '供应商详情获取失败');
                }
                $supplier = json_decode($supplier);
                $where_month_payroll = [];
                $where_month_payroll [] = ['bill_number', '=', $param['bill_number']];
                $where_month_payroll [] = ['supplier_id', '=', $param['supplier_id']];
                $where_month_payroll [] = ['supplier_type', '=', $param['supplier_type']];
                $where_month_payroll [] = ['payroll_requisition_type', '=', 3]; // 请款类型
                $where_month_payroll [] = ['month', '=', $month]; // 获取当前月份
                $where_month_payroll [] = ['year', '=', $year]; // 获取当前年份
                $where_month_payroll [] = ['status', '<', 4];
                $check_month_payroll = WaPurchasePayrollRequisition::findReadyBack($where_month_payroll);
                if ($check_month_payroll){
                    return IndexController::errored('', '当前月份月结请款账单已存在');
                }

            }else{
                return IndexController::errored('', '缺少必要入参-> 供应商 type / id');
            }
        } else {
            return IndexController::errored('', '缺少必要入参-> 供应商 type / id');
        }


        PublicCommentController::请款单请款结算类型;
        // 创建采购请款单数据
        $payroll_requisition_data = [
            'bill_number' => $param['bill_number'],
            'supplier_id' => $param['supplier_id'], // 收款公司id
            'supplier_type' => $param['supplier_type'], // 收款公司类型
            'payroll_requisition_type' => 3, //请款类型
            'purchase_payroll_sn' => $purchase_payroll_sn, //采购请款编号
            'admin_id' => $adminId->id, //管理员id
            'admin_name' => $adminId->nickname, //管理员名称
            'payment_company_type' => $param['payment_company_type'], // 付款方类型 1 挂靠公司 2 出口公司 3 其它
            'payment_company_name' => $payment_company_name, // 付款公司名称
            'payment_id' => $param['payment_id'], // 付款公司id
            'price_name' => $param['price_name'], //款项名称
            'total_price' => round($param['total_price'], 2), //总金额
            'requested_price' => round($param['total_price'], 2), //已请款金额
            'this_request_price' => round($param['total_price'], 2), //本次请款金额
            'remark' => $param['remark'],
            'status' => 2, // //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
            'created_at' => dateTime(),

            'month' => $month,
            'year' => $year,
        ];


        if (array_key_exists('payment_company_info',$param)){
            $payroll_requisition_data['payment_company_info'] = json_encode($param['payment_company_info']);
        }

        if (array_key_exists('collecting_company_info',$param)){
            $payroll_requisition_data['collecting_company_info'] = json_encode($param['collecting_company_info']);
        }


        if ($supplier) {
            $payroll_requisition_data['supplier_id'] = intval($supplier->id);
            $payroll_requisition_data['supplier_name'] = $supplier->name;// 收款公司名称
            $payroll_requisition_data['supplier_type'] = $param['supplier_type'];
//            $payroll_requisition_data['supplier_phone'] = $supplier->phone;
//            $payroll_requisition_data['supplier_linkman'] = $supplier->linkman;
        }

        \support\Db::beginTransaction();
        try {
            $res = WaPurchasePayrollRequisition::created($payroll_requisition_data);
            // 提交审批   超出采购金额  端午前改版了  所有金额都需要审批
            $add_by_month = ApproveSettingController::payrollApproveAddByMonth($adminId,$param['total_price'],$param,$purchase_payroll_sn,$param['bill_number']);
            if ($add_by_month != 'true'){
                return IndexController::errored('', $add_by_month);
            }



            $where_monthly_settlement = [];
            $where_monthly_settlement [] = ['supplier_id','=', $supplier->id];
            $where_monthly_settlement [] = ['supplier_name','=', $supplier->name];
            $where_monthly_settlement [] = ['supplier_type','=', $param['supplier_type']];
            $where_monthly_settlement [] = ['month','=', $month];
            $where_monthly_settlement [] = ['year','=', $year];

            // 修改月结状态信息
            $monthly_settlement_data= [
                'purchase_payroll_sn' => $purchase_payroll_sn, // 请款编号
                'settlement_sratus' => 1, // 结算状态 1 待结算 2 已结算 4 删除
                'updated_at' => dateTime(),
            ];
            WaMonthlySettlement::updated($monthly_settlement_data,$where_monthly_settlement);
            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '月结付款', // 标题
                        'markdown' => '月结请款'.$time, // 内容
                    ];
                    $currentRoute  = $request->host();

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed($res, '采购请款单创建成功');
        } catch (\Throwable $exception) {

            IndexController::logError('monthlySettlementPayrollReurchaseCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '采购请款单创建失败');
        }

    }

    /**
     * 请款单状态修改
     * @param Request $request
     * @return Response
     */
    public function purchasePayrollRequisitionStatusUpdate(Request $request)
    {
//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 根据采购请款单编号获取订单信息
        $orders = WaPurchasePayrollRequisition::find(['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取采购请款单信息失败');
        }


        // 获取当前用户对应部门所设置的审批流设置
        if (array_key_exists('sort', $param)){
            if ($param['sort']){
                $sort = $param['sort'];
            }else{
                $sort = 0;
            }
        }else{
            $sort = 0;
        }
        if (array_key_exists('flow',$param)){
            $flow = $param['flow'];
            $admin_ids = json_encode($flow[0]['approve_admin_id']);
            $send_after = $param['send_after'];
            $send_before = $param['send_before'];
//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息


        }else{
            if (array_key_exists('sort', $param)){
                if ($param['sort']){
                    $sort = $param['sort'];
                }else{
                    $sort = 0;
                }
            }else{
                $sort = 0;
            }
            $flow = ApproveSettingController::flowSttingBySort(6,$sort);// sort默认选第一个
            $send_after = ApproveSettingController::flowSttingBySendBefore(6,$sort);// 抄送人 - 前 默认选第一个
            $send_before = ApproveSettingController::flowSttingBySendAfter(6,$sort);// 抄送人 - 前 默认选第一个
            $admin_ids = json_encode($flow[0]->approve_admin_id);
        }
        if (!$flow) {
            return IndexController::errored('', '未获取采购请款单的审批流');
        }


        \support\Db::beginTransaction();
        try {
            // 采购请款单状态 0 草稿(撤回审批)  1 审批中(提交审批) 2 待付款 3 已付款 4 审核不通过 5 删除
            if ($param['status'] == 0) {
                // 0 草稿
                if (intval($orders->status) != 1) {
                    return IndexController::errored('', '只有审批中才能撤回');
                }
                // 采购请款单回到草稿状态
                $up_wppr = WaPurchasePayrollRequisition::updated(['status' => 0, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $param['purchase_payroll_sn']]); // 待审核
                if (!$up_wppr) {
                    return IndexController::errored('', '采购请款单回到草稿状态失败');
                }

                // 采购审批单 审核状态变成已撤回
                $up_wprea = WaPayrollRequisitionExamineApprove::updated(['purchase_payroll_sn' => $param['purchase_payroll_sn']], ['status' => 3, 'updated_at' => dateTime()]);
                if (!$up_wprea) {
                    return IndexController::errored('', '审核状态变成已撤回状态失败');
                }

                // 采购审批日志 添加审批驳回记录
                $check = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
                $check = json_decode($check);
                if (!$check) {
                    return IndexController::errored('', '无法获取该订单的审批数据');
                }
                $approve_log_data = [
                    'pr_no' => $check->pr_no, // 采购请款单编号
                    'check_id' => $check->id, // 审核id
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'status' => 3, //待审核 1审批通过 2 审批驳回 3 撤回 4  删除
                    'refuse_reason' => '审批被撤销',
                ];

                if ($param['purchase_payroll_sn']) {
                    $approve_log_data['purchase_payroll_sn'] = $param['purchase_payroll_sn'];// 采购请款单编号
                }
                $res = WaPayrollRequisitionExamineApproveFlow::create($approve_log_data);
            } elseif ($param['status'] == 1) {
                // 1审批中(提交审批):
                // 创建新的采购请款单审批 -> 创建采购请款单审批流第一条待审核记录
                // 判断 采购请款单的状态 是否符合创建审核条件 是否同一笔审批未结束 采购请款单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
                $checkPurchaseApprove = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
                $checkPurchaseApprove = json_decode($checkPurchaseApprove);
                if ($checkPurchaseApprove) {
                    if ($checkPurchaseApprove->status == 0 && $checkPurchaseApprove->status == 1) {
                        return IndexController::errored('', '该订单在审核流程中不能重复创建');
                    }
                }

                $pr_no = 'PR' . IndexController::getRandomNum(6);

                $data = [
                    'pr_no' => $pr_no, // 采购请款单编号
                    'total_amount' => $orders->total_price, // 订单金额
                    'admin_id' => $adminId->id, // 创建人id(提交订单审批的创建人)
                    'admin_name' => $adminId->nickname, // 创建人名称
                    'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                    'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
                    'approve_flow' => json_encode($flow), // 当前采购请款单的审批流流程
                    'initiator_admin_name' => $adminId->nickname, // 审批发起人
                ];

                if ($send_before){
                    $data['approve_flow_send_before'] = json_encode($send_before);
                }
                if ($send_after){
                    $data['approve_flow_send_after'] = json_encode($send_after);
                }
                if ($param['purchase_payroll_sn']) {
                    $data['purchase_payroll_sn'] = $param['purchase_payroll_sn'];// 采购请款单编号
                }

                $up_PurchaseEa = WaPayrollRequisitionExamineApprove::updated(['pr_no' => $pr_no, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
                if (!$up_PurchaseEa) {
                    return IndexController::errored('', '更新采购请款单审批驳回');
                }

                // 创建审批流 1供应商审批 2销售订单审批 3销售合同审批 4采购请款单审批 5采购合同审批 6采购请款审批 7交强险请款审批
//            // 采购请款单审流 创建 (创建审批流中的第一个审批)
                $approve_log_data = [
                    'pr_no' => $pr_no, // 采购请款单编号
                    'check_id' => $up_PurchaseEa, // 审核id
                    'admin_ids' => $admin_ids, //
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'initiator_admin_name' => $adminId->nickname, // 审批发起人
                    'status' => 0, //待审核 1审批通过 2 审批驳回  4  删除
                    'describe' => '待' . $admin_ids . '审核',

                ];

                if ($param['purchase_payroll_sn']) {
                    $approve_log_data['purchase_payroll_sn'] = $param['purchase_payroll_sn'];// 采购请款单编号
                }
                $res = WaPayrollRequisitionExamineApproveFlow::create($approve_log_data);
                if (!$res) {
                    return IndexController::errored('', '创建采购请款单审批流失败');
                }
                $up_payroll = WaPurchasePayrollRequisition::updated(['status' => 1, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
                if (!$up_payroll) {
                    return IndexController::errored('', '请款单状态修改失败');
                }
            } elseif ($param['status'] == 2) {
                // 待付款(审批通过后修改的订单状态只能 审核列表操作)
                return IndexController::errored('', '该状态,只能审批通过自动修改');
            } elseif ($param['status'] == 3) {
                //3 已付款(确认付款操作)
                return IndexController::errored('', '该状态,确认付款接口修改');
            } elseif ($param['status'] == 4) {
                //4 审核不通过(审批驳回后修改的订单状态只能 审核列表操作)
                return IndexController::errored('', '该状态,只能审批驳回自动修改');
            } elseif ($param['status'] == 5) {
                //5 撤回
                return IndexController::errored('', '该状态,有单独的撤回接口');
            } elseif ($param['status'] == 6) {
                //6 删除  只有草稿才能删除 只需要修改当前主订单状态就行
                if (intval($orders->status) != 0) {
                    return IndexController::errored('', '只有草稿才能删除');
                }
                $del = WaPurchasePayrollRequisition::updated(['status' => 5, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $param['purchase_payroll_sn']]); // 待审核
                if (!$del) {
                    return IndexController::errored('', '草稿删除失败');
                }
            } else {
                return IndexController::errored('', '该状态不存在');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新成功');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasePayrollRequisitionStatusUpdate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 请款单确认付款
     * 修改订单装完为已完成 但是只能代付款状态下确认收货后操作 需要入参
     * @param Request $request
     */
    public function payrollRequisitionConfirmPay(Request $request)
    {

        //        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 根据采购请款单编号获取订单信息
        $payroll_orders = WaPurchasePayrollRequisition::find(['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
        $payroll_orders = json_decode($payroll_orders);
        if (!$payroll_orders) {
            return IndexController::errored('', '获取采购请款单信息失败');
        }

        $payment_voucher = json_encode($param['payment_voucher']);
        \support\Db::beginTransaction();
        try {
            // 获取付款人账号
            $payment_company_info = $payroll_orders->payment_company_info;
            if ($payment_company_info){
                $payment_account = $payment_company_info->payment_account;
            }else{
                return IndexController::errored('', '缺少付款人账号');
            }
            $data = [
                'confirm_pay_time' => dateTime(), // 确认付款时间
                'payment_account' => $payment_account, // 收款账号
                'this_request_price' => round($payroll_orders->this_request_price, 2), // 本次请款金额
                'payment_voucher' => $payment_voucher, // 付款凭证
                'payment_remark' => $param['payment_remark'], // 备注

                'updated_at' => dateTime(), //
                'finance_admin_id' => $adminId->id, //
                'finance_admin_name' => $adminId->nickname, //

                'status' => 3 //已付款   0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除
            ];

            // 第一点 ：判断是不是 采购定金 (超过或等于额定金额即为完成进入下一个状态)
            // 第二点 ：判断是不是尾款
            // 第三点 ：判断采购请款单的是否是月结订单 （月结订单有 结算状态需要同步更新才能展示  要不就得遍历所有请款单比较麻烦）

            if ($payroll_orders->price_name == '采购定金') {
                // 判断请款金额是佛大于等于定金
                $total_price = round($payroll_orders->total_price, 2);
                $requested_price = round($payroll_orders->requested_price, 2);
                $this_request_price = round($payroll_orders->this_request_price, 2);
                $where = [];
                $where [] = ['purchase_order_sn','=', $payroll_orders->purchase_order_sn];
                $where [] = ['price_name','=', $payroll_orders->price_name];
                $requested_price =  WaPurchasePayrollRequisition::sums($where); // 已请款金额
                $new_total_price = $requested_price + round($payroll_orders->this_request_price, 2);
                // 当总定金额超过或等于额定定金金额 即为定金请款完成 但采购订单未完成(重点) 但是目前定金只能请款一次 只要一笔该订单的定金总额与额定相同就进入下一个状态
                if ($new_total_price >= $total_price){
                    $orders_purchase_condition =[];
                    $orders_purchase_condition [] = ['purchase_order_sn','=', $payroll_orders->purchase_order_sn];
                    PublicCommentController::采购订单状态;//采购订单状态定义
                    $orders_purchase_data = [
                        'purchase_orders_status' => 5,
                        'updated_at' => dateTime(),
                    ];
                    $res = WaOrdersPurchase::updated($orders_purchase_data, $orders_purchase_condition);
                    if (!$res) {
                        return IndexController::errored('', '更新采购订单定金付款转态失败');
                    }
                    // 添加定金请款到采购订单费用明细
                    $orders_purchase_data = [
                        'status' => 3,
                        'price_name' => '定金请款',
                        'admin_id' => $payroll_orders->admin_id, // 请款人 和 明细里的创建人是同一个人
                        'admin_name' => $payroll_orders->admin_name,
                        'total_amount' => $payroll_orders->total_price,
                        'purchase_order_sn' => $payroll_orders->purchase_order_sn,
                        'created_at' => dateTime(),
                    ];
                    $orders_purchase_add = WaOrdersPurchaseAmountDetail::created($orders_purchase_data);
                    if (!$orders_purchase_add) {
                        return IndexController::errored('', '添加定金请款到采购订单明细');
                    }

                }
            }elseif ($payroll_orders->price_name == '采购尾款') {
                PublicCommentController::采购订单状态;
                $orders_purchase_condition =[];
                $orders_purchase_condition [] = ['purchase_order_sn','=', $payroll_orders->purchase_order_sn];
                $orders_purchase_data = [
                    'purchase_orders_status' => 6, // 已完成
                    'updated_at' => dateTime(),
                ];
                $res = WaOrdersPurchase::updated($orders_purchase_data, $orders_purchase_condition);
                if (!$res) {
                    return IndexController::errored('', '更新采购订单尾款付款转态失败');
                }
                // 添加尾款请款到采购订单费用明细
                $orders_purchase_data = [
                    'status' => 3,
                    'price_name' => '尾款请款',
                    'admin_id' => $payroll_orders->admin_id, // 请款人 和 明细里的创建人是同一个人
                    'admin_name' => $payroll_orders->admin_name,
                    'total_amount' => $payroll_orders->total_price,
                    'purchase_order_sn' => $payroll_orders->purchase_order_sn,
                    'created_at' => dateTime(),
                ];
                $orders_purchase_add = WaOrdersPurchaseAmountDetail::created($orders_purchase_data);
                if (!$orders_purchase_add) {
                    return IndexController::errored('', '添加尾款请款到采购订单明细');
                }

            }
            if (!in_array($payroll_orders->price_name,['采购定金','采购尾款'])){
                PublicCommentController::请款单请款结算类型;
                if ($payroll_orders->payroll_requisition_type == 3) {
                    $monthly_settlement_condition = [];
                    $monthly_settlement_condition [] = ['bill_number', '=', $payroll_orders->bill_number];
                    $monthly_settlement_data = [
                        'settlement_sratus' => 3,// （作废 在列表中自定义生成）结算状态 1 未结清 2 结款中(请款创建、作废需要修改) 3 已结清(财务付款需要修改) 4 撤回(即删除 订单中的状态需求变回待请款)
                        'updated_at' => dateTime(),
                    ];
                    $monthly_settlement_up = WaMonthlySettlement::updated($monthly_settlement_data, $monthly_settlement_condition);
                    if (!$monthly_settlement_up) {

                        return IndexController::errored('', '月结结算状态同步失败');
                    }
                }elseif ($payroll_orders->payroll_requisition_type == 1){
                    $cash_settlement_condition = [];
                    $cash_settlement_condition [] = ['vin','=',$payroll_orders->vin];
                    $cash_settlement_condition [] = ['price_name','=',$payroll_orders->price_name];
                    $cash_settlement_data=[
                        'payment_status' => 3,// 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
                        'updated_at' => dateTime(),
                    ];
                    $cash_settlement_up = WaPurchasedVehiclesAmountDetail::updated($cash_settlement_data,$cash_settlement_condition);
                    if (!$cash_settlement_up) {

                        return IndexController::errored($payroll_orders->price_name, '现结结算状态同步失败');
                    }
                }
            }



            $res = WaPurchasePayrollRequisition::updated($data, ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
            if (!$res) {

                return IndexController::errored('', '确认付款失败');
            }


            \support\Db::commit();
            return IndexController::successed('', '确认付款成功');
        } catch (\Throwable $exception) {

            IndexController::logError('payrollRequisitionConfirmPay', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '确认付款失败');
        }
    }

    /**
     * 请款单撤回
     * @param Request $request
     * @return Response
     */
    public function payrollRequisitionWithdraw(Request $request)
    {
//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));


        \support\Db::beginTransaction();
        try {
            // 根据采购请款单编号获取订单信息

            $condition_payroll = [];
            $condition_payroll [] = ['purchase_payroll_sn', '=', $param['purchase_payroll_sn']];

            $payroll_data = WaPurchasePayrollRequisition::find($condition_payroll);
            $payroll_data = json_decode($payroll_data);
            if (!$payroll_data) {
                return IndexController::errored('', '获取采购请款单信息失败');
            }

            PublicCommentController::请款单请款结算类型;
            if ($payroll_data->payroll_requisition_type == 1 && $payroll_data->payroll_requisition_type == 2){
//                PublicCommentController::车辆明细付款类型;
//                $cash_status_condition = [
//                    'payment_status' => 5,
//                    'updated_at' => dateTime(),
//                ];
//
//                $up = WaPurchasedVehiclesAmountDetail::updated($cash_status_condition,$condition_payroll);
//                if (!$up) {
//                    return IndexController::errored('', '撤回现结请款单失败');
//                }

            }elseif ($payroll_data->payroll_requisition_type == 3){
                // 月结
                PublicCommentController::月结订单结算状态;
                $month_status_condition = [
                    'settlement_sratus' => 4,
                    'updated_at' => dateTime(),
                ];

                $up = WaMonthlySettlement::updated($month_status_condition,$condition_payroll);
                if (!$up) {
                    return IndexController::errored('', '撤回月结请款单失败');
                }

            }elseif ($payroll_data->payroll_requisition_type >= 4){
                // 车务撤回现结请款单失败
                PublicCommentController::车辆明细付款类型;
                $cash_status_condition = [
                    'payment_status' => 5,
                    'updated_at' => dateTime(),
                ];

                $up = WaPurchasedVehiclesAmountDetail::updated($cash_status_condition,$condition_payroll);
                if (!$up) {
                    return IndexController::errored('', '撤回现结请款单失败');
                }
            }

            $condition_payroll_data = [
                'status' => 5,
                'updated_at' => dateTime(),
            ];

            $up = WaPurchasePayrollRequisition::updated($condition_payroll_data,$condition_payroll);
            if (!$up) {
                return IndexController::errored('', '撤回月结请款单失败');
            }

            // 审批记录 和审批流记录 修改成撤回状态
            $payroll_approve = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
            $payroll_approve = json_decode($payroll_approve);
            if ($payroll_approve) {
                //删除审批
                PublicCommentController::请款单状态;
                PublicCommentController::请款审批状态;
                $condition_prea = [];
                $condition_prea [] = ['purchase_payroll_sn', '=', $param['purchase_payroll_sn']];
                $prea_data = [
                    'status' => 3,
                    'updated_at' => dateTime(),
                ];
                $prea_up = WaPayrollRequisitionExamineApprove::updated($condition_prea,$prea_data);
                if (!$prea_up){
                    return IndexController::errored('', '审批状态修改失败');
                }

                $condition_prea_flow = [];
                $condition_prea_flow [] = ['purchase_payroll_sn','=', $param['purchase_payroll_sn']];
                $prea_flow_data = [
                    'status' => 3,
                    'updated_at' => dateTime(),
                ];
                $prea_flow_up = WaPayrollRequisitionExamineApproveFlow::updated($condition_prea_flow,$prea_flow_data);
                if (!$prea_flow_up){
                    return IndexController::errored('', '审批流状态修改失败');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '撤销成功');
        } catch (\Throwable $exception) {

            IndexController::logError('payrollRequisitionWithdraw', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '撤销失败');
        }

    }


    /**
     * 现结付款列表
     * @param Request $request
     * @return Response
     */
    public function purchasePayrollRequisitionList(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        $condition = [];
        $between = [];

        if (array_key_exists('purchase_payroll_sn', $param)) {
            if ($param['purchase_payroll_sn']) {
                $condition [] = ['purchase_payroll_sn', '=', $param['purchase_payroll_sn']];
            }
        }

//        if (array_key_exists('purchase_order_sn', $param)) {
//            $condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
//        }

        if ($param['admin_name']) {
            $condition [] = ['admin_name', 'like', '%' . $param['admin_name'] . '%'];
        }

        if ($param['supplier_name']) {
            $condition [] = ['supplier_name', 'like', '%' . $param['supplier_name'] . '%'];
        }
        if ($param['status'] || $param['status'] == 0) {
            $condition [] = ['payroll.status', '=', $param['status']];
        }
        $condition [] = ['payroll.status', '!=', 5];
        PublicCommentController::请款单请款结算类型;
        $condition [] = ['payroll.payroll_requisition_type', '!=', 3]; // 请款类型


//        if ($param['start_time'] && $param['end_time']) {
//            $between [] = ['payroll.created_at', '>', $param['start_time']];
//            $between [] = ['payroll.created_at', '<', $param['end_time']];
//        }

        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $whereIn = [];
        if (in_array($adminId->department_id, [44, 45])) { // 采购部 国际物流部
            $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
            $whereIn = $next_epartment_members;
        }

//        $fields = ['payroll.*', 'amount_detail.admin_name as create_name'];
        $fields = ['payroll.*'];
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $listOrder = WaPurchasePayrollRequisition::list($adminId, $page, $pageNum, $whereIn, $fields, $condition, $between);
        return IndexController::successed($listOrder, '采购请款单列表');

    }

    /**
     * 采购请款单详情
     * @param Request $request
     * @return Response
     */
    public function purchasePayrollRequisitionDetail(Request $request)
    {
        $param = $request->all();
        // 主订单信息
        $orderParentData = WaPurchasePayrollRequisition::find(['purchase_payroll_sn' => $param['purchase_payroll_sn']]);
        if (!$orderParentData) {
            return IndexController::errored('', '采购请款单信息获取失败');
        }

        return IndexController::successed($orderParentData, '采购请款单列表');

    }


}